#!/bin/sh
#
#	Start Stop Restart script for CrossLight
#	Andrew Niemantsverdriet
#	David Souther

### BEGIN INIT INFO
# Provides:          crosslight
# Required-Start:    $local_fs
# Default-Start:     2 3 4 5 S
# Default-Stop:      0 1 6
# Short-Description: Crosslight is a minimal Lighttpd/PHP server
# Description:       Crosslight provides a small, easy to configure
#	HTTP server with a PHP backend.
### END INIT INFO

#Set the root directory to be where the script is run from
export ROOTDIR="`pwd`"

# Default values
PORT=3000
ALL=
SUDO=

if [[ $EUID -eq 0 ]] ; then
	PORT=80 #Default to 80 for root user
fi

# Error codes
SITE_CONFIGURATION_UNAVAILABLE=1
USER_ARG_ERROR=2
USAGE=3

# Set values
SELF=$0
ACT=$1
shift

usage()
{
	echo "$SELF: Crosslight Cross-platform PHP development environment."
	echo "Usage:"
	echo "	$SELF {start|restart|debug} [-p port]	Start, and optionally choose port."
	echo "	$SELF stop [-a]	Stop crosslight. -a force-kills all running instances."
	echo "	$SELF status	Print status info about Crosslight."
	echo "	$SELF {setup|install}	Configure username."
	echo "	$SELF service	Run chkconfig to make Crosslight a service."
	echo "	$SELF site ...	Manage sites for this Crosslight install. Run with no site for usage."
}

site_usage()
{
	echo "$SELF site: Configure available Crosslight sites."
	echo "Usage:"
	echo "	$SELF site {-|default} <appname> </path/to/app> [-h]"
	echo "		Create a new site configuration. Document root will use /path/to/app."
	echo "		Configuration will be available under etc/sites/sites.d/appname.conf. If the -h flag is used,"
	echo "		'127.0.0.1	appname.localhost' will be added to the hosts file (will prompt	for sudo password)."
	echo "	$SELF site prep <appname>	Ensure appropriate folders and files are available in var/"
	echo "	$SELF site host <appname>	'127.0.0.1	appname.localhost' will be added to the hosts file"
	echo "		(will prompt for sudo password)."
	echo
	echo "	$SELF site clean app1 [app2...]	Completely remove named apps from this install. Does not"
	echo "		affect the source directory."
	echo
	echo "	$SELF site enable [appname]	Enable the site configuration, so it will get served."
	echo "		Lists available sites in sites.d if no appname given. Requires restart to load new config."
	echo "	$SELF site disable [appname]	Disable the site configuration, so it will not get served."
	echo "		Lists enabled sites in enabled.d if no appname given. Requires restart to load new config."
	echo
	echo "Special usage:"
	echo "	$SELF site kohana <appname> </path/to/app> [-h]"
	echo "		Create a site configuration for a Kohana (or similar PHP routing) application."
	echo "		As 'site default', but additionally downloads and installs current Kohana in"
	echo "		/path/to/app if empty, and creates rewrite rules to append path as param to index.php."

}

#Parse Arguments
while getopts "ahsp:" OPT ; do
    case $OPT in
        h) usage; exit $USAGE ;;
        p) PORT=$OPTARG ;;
        a) ALL="ALL" ;;
		s) SUDO="sudo";;
    esac
done

findport()
{
	#Find available Port
	netstat --tcp --listening --numeric-hosts --numeric-ports | awk '{print $4}' | fgrep ":$PORT" >/dev/null 2>&1
	AVAIL=$?
	while [ $AVAIL -eq 0 ] ; do
		PORT=$(($PORT + 1))
		netstat --tcp --listening --numeric-hosts --numeric-ports | awk '{print $4}' | fgrep ":$PORT" >/dev/null 2>&1
		AVAIL=$?
	done
}

case "$ACT" in
	start|debug)
		if [ -e $ROOTDIR/var/tmp/lighttpd.pid ]
			then echo "Can not start CrossLight it is already running"
		else
			D=''
			if [ "$ACT" = "debug" ]
			then
				#D='-D'
				echo -n
			fi
			findport
			echo "# AUTOGENERATED FILE, DO NOT EDIT" >| $ROOTDIR/etc/lighttpd.conf.local
			echo "rootdir = \"$ROOTDIR\"" >| $ROOTDIR/etc/lighttpd.conf.local
			echo "server.port = $PORT" >> $ROOTDIR/etc/lighttpd.conf.local
			if [ "$ACT" = "debug" ]
			then
				echo "include rootdir + \"/etc/lighttpd.debug.conf\"" >> $ROOTDIR/etc/lighttpd.conf.local
				echo "CrossLight in Debug mode."
			fi
			echo "CrossLight started at localhost:$PORT"
			$SUDO $ROOTDIR/bin/lighttpd $D -f $ROOTDIR/etc/lighttpd.conf -m ./bin/lib/
			if [ "$ACT" = "debug" ]
			then
				tail -f $(find $ROOTDIR/var/log/ -type f -name '*log')
				$SELF stop
			fi
		fi
	;;

	stop)
		if [ -e $ROOTDIR/var/tmp/lighttpd.pid ]
		then
			kill $(cat $ROOTDIR/var/tmp/lighttpd.pid) 2>&1 > /dev/null
			$(rm -f $ROOTDIR/var/tmp/lighttpd.pid)
			echo "CrossLight has been stopped"
		else
			echo "CrossLight not currently running in this installation."
		fi

		if [ "$ALL" = "ALL" ]
		then
			killall lighttpd
			echo "Force-killed all lighttpds."
			echo "If a different lighttpd was open, its pid did not get cleaned up."
			echo "If you run a different crosslight install, and get 'already running'"
			echo "you will need to run ./crosslight.sh stop or ./crosslight.sh restart."
			echo "If you had non-crosslight lighttpds, you will need to take appropriate"
			echo "measures for those servers, as well."
		fi
	;;

	status)
		if [ -e $ROOTDIR/var/tmp/lighttpd.pid ]
			then echo "CrossLight is running"
			else echo "CrossLight is stopped"
		fi
	;;

	restart)
		$ROOTDIR/crosslight.sh stop
		$SUDO $ROOTDIR/crosslight.sh start -p $PORT
	;;

	install|setup)
		UN=$(whoami)
		GN=$(id --group --name)
		read -p "Crosslight Username ($UN): " UN
		read -p "Crosslight Groupname ($GN): " GN
		[ -z $UN ] && UN=$(whoami)
		[ -z $GN ] && GN=$(id --group --name)
		sed -i "s/server.username = \"CHANGEME\"/server.username = \"$UN\"/" etc/lighttpd.conf
		sed -i "s/server.groupname = \"CHANGEME\"/server.groupname = \"$GN\"/" etc/lighttpd.conf
	;;

	site)
		SITE=$1 ; shift
		APP=$1 ; shift
		ROOT=$1 ; shift
		if [ "${SITE}x" == "x" ]
		then
			site_usage
			exit $USER_ARG_ERROR
		elif [ ! -d $ROOTDIR/opt/site/$SITE ]
		then
			echo "{$SITE} is not an available site configuration."
			exit $SITE_CONFIGURATION_UNAVAILABLE
		fi
		if [ ! -d $ROOTDIR/var/sites ]
		then
			mkdir -p $ROOTDIR/var/sites
		fi
		$ROOTDIR/opt/site/$SITE/build.sh "$APP" "$ROOT"
	;;

	*)
		usage
		exit $USAGE
	;;
esac
